package stewardapp

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/devices"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/onlinesig"
	"yundian/internel/pkg/utils"
)

// HandleDrawDeviceDiscounts 领取设备优惠记录
func HandleDrawDeviceDiscounts(ctx *gin.Context) {
	param := make(request.DrawDeviceDiscountsReq)
	dingo.ErrorIf(ctx.ShouldBindJSON(&param)).Unwrap()
	param["secret"] = "z0m903526004ce4b0est1a3940f5f92"

	timeNum, _ := strconv.Atoi(param["time"])
	if (int64(timeNum) + 10) < time.Now().Unix() {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}

	// deviceSn date openId uuid sing
	paramStr := utils.EncodeAliPaySignParams(param)
	sing := onlinesig.MD5(paramStr)
	if sing != param["sing"] {
		Response(ctx)("验签失败", CodeInvalidParam, nil)(OK)
		return
	}

	deviceInfo := dao.NewDeviceDao().GetDeviceByDeviceSn(param["deviceSn"]).Unwrap().(*devices.DeviceModel)
	if deviceInfo.ID <= 0 || deviceInfo.PlaceId == 0 {
		Response(ctx)("设备号错误", CodeInvalidParam, nil)(OK)
		return
	}

	param["type"] = "1"
	if data := dao.NewDeviceDiscountsDao().DrawDeviceDiscountsRecord(param); data.Err != nil {
		Response(ctx)(data.Err.Error(), CodeInvalidParam, nil)(OK)
		return
	}

	pwdData := logic.NewDeviceLogic().HandleGetPasswordWxCoupon(deviceInfo.DeviceSn, 20)
	Response(ctx)("", CodeSuccess, pwdData)(OK)
}
